<?php
/**
 * 获取医嘱模型
* @authors xiadx (xiadx@zpdchina.com)
* @date    2017-03-03 10:07:25
* @version $Id$
*/

class YizhuAllInfoModel extends BaseModel {

	/**
	 * 根据科室、组号、住院ID、修改时间获取医嘱信息
	 * @param  [type] $user_department    [description]
	 * @param  [type] $user_department_id [description]
	 * @param  [type] $modify_time        [description]
	 * @param  array  $zuhao_arr          [description]
	 * @return [type]                     [description]
	 */
	public function getAllYizhu($user_department, $user_department_id, $modify_time, $jsonData)
	{
		/////////
		//TODO 配置参数需处理//
		/////////
		// 长期查询条件字符串
		$chaxun_changqi_where = '';
		// 临时查询条件字符串
		$chaxun_linshi_where = '';

		$yiyuan_id = $this->yiyuan_id;
		$where_yiyuan_id = ' t.yiyuan_id = ' . $yiyuan_id;
		if(!empty($user_department_id)){
			$chaxun_changqi_where .= " AND t.zhuyuan_id = '$user_department_id'";
			$chaxun_linshi_where .= " AND t.zhuyuan_id = '$user_department_id'";
		}

		if($user_department){
			$chaxun_changqi_where .= " AND t.zhuyuan_bingqu = '$user_department'";
			$chaxun_linshi_where.= " AND t.zhuyuan_bingqu = '$user_department'";
		}

		if($modify_time){
			$chaxun_changqi_where .= " AND a.modify_time >= '$modify_time'";
			$chaxun_linshi_where.= " AND a.modify_time >= '$modify_time'";
		}

		if(!empty( $jsonData)){
			$data = json_decode($jsonData,true);
			$chaxun_changqi_where .= " AND a.zuhao NOT IN ('".implode("','", $data) . '\')';
			$chaxun_linshi_where .= " AND a.zuhao NOT IN ('".implode("','", $data) . '\')';
		}

		$huanzhe_where = " AND t.zhuangtai = '住院中' ";
		$huanzhe_chuyuan_baoliu_shijian = Yaconf::get("config$yiyuan_id.huanzhe_chuyuan_baoliu_shijian");
		if($huanzhe_chuyuan_baoliu_shijian){
			$huanzhe_where = " AND (t.zhuangtai = '住院中' or (t.zhuangtai = '已出院' and ".Utility::getIntervalSqlString("t.chuyuan_riqi_time",$huanzhe_chuyuan_baoliu_shijian).")) ";
		}

		/*长期*/
		$time = intval (date("Hi"));
		$show_new_yizhu = Yaconf::get("config$yiyuan_id.show_new_yizhu");
        $zhuyuan_yizhu_changqi_data = array();
		if($time >= intval($show_new_yizhu)){
			$changqi_str = '';
			$interval = Yaconf::get("config$yiyuan_id.changqi_yizhu_tingzhi_baoliu_shijian");
			$str = Utility::getIntervalSqlString("a.stop_time",$interval);
			$changqi_str_ing = " AND a.state = '开始执行'";
			$changqi_str = " AND (a.state='停止执行' AND ".$str;
			/*if(C('changqi_start_end_time_diff_no_need')){
			 $chaxun_changqi['_string'] .= "(UNIX_TIMESTAMP(a.stop_time) - UNIX_TIMESTAMP(a.start_time))>=".C('changqi_start_end_time_diff_no_need');
			 }*/
			$changqi_str .= ")";
			// 开始执行
			$chaxun_changqi_where_ing = $chaxun_changqi_where . $changqi_str_ing;
			// 停止执行
			$chaxun_changqi_where_stop = $chaxun_changqi_where . $changqi_str;

			//医嘱表增加相应dx2016-07-12增加返回字段chushi_state
			$filed_str_changqi = "a.id,a.zhuyuan_id,'长期' type,a.content,a.start_time,a.stop_time,a.yongfa,a.yongfa_type,a.ciliang,a.shiyong_danwei,a.pinlv,a.zuhao,a.zhixing_state,a.yizhu_yongfa_type,a.meiri_cishu,a.wancheng_cishu,a.beizhu,a.xiangying_state,a.state,a.chushi_state,a.modify_time,a.shouci_yongyao,a.yongyao_time,a.shenhe_hushi_id";
			// 长期的开始执行医嘱 SQL
			$sql_ing = "SELECT $filed_str_changqi FROM zhuyuan_basic_info as t LEFT JOIN zhuyuan_yizhu_changqi AS a ON t.zhuyuan_id=a.zhuyuan_id WHERE $where_yiyuan_id $huanzhe_where $chaxun_changqi_where_ing ";
			// 长期的停止执行医嘱的sql
			$sql_stop = "SELECT $filed_str_changqi FROM zhuyuan_basic_info as t LEFT JOIN zhuyuan_yizhu_changqi AS a ON t.zhuyuan_id=a.zhuyuan_id WHERE $where_yiyuan_id $huanzhe_where $chaxun_changqi_where_stop ";
            // 长期的开始执行
            $zhuyuan_yizhu_changqi_data_ing = DB::query(Database::SELECT, $sql_ing)->execute()->as_array();
            // 长期的停止执行
            $zhuyuan_yizhu_changqi_data_stop = DB::query(Database::SELECT, $sql_stop)->execute()->as_array();
            // $zhuyuan_yizhu_changqi_data_stop = [];
            $zhuyuan_yizhu_changqi_data = array_merge($zhuyuan_yizhu_changqi_data_ing, $zhuyuan_yizhu_changqi_data_stop);
            /*end*/
		}


		/*临时医嘱*/
		$zhuyuan_yizhu_linshi_data = [];
		$show_linshi_24_hour = Yaconf::get("config$yiyuan_id.show_linshi_24_hour");//临时医嘱24小时显示
		$interval = Yaconf::get("config$yiyuan_id.mobileemr_transfer_interval_yizhu_linshi");

		$linshi_str = Utility::getIntervalSqlString("a.xiada_time",$interval);
		if($show_linshi_24_hour == true){
			$chaxun_linshi_where .= ' AND ' . $linshi_str;
			$chaxun_linshi_where .= " AND a.state in('开始执行','停止执行')";
		} else {
			// 获取配置信息
			$stop_linshi_interval = Yaconf::get("config$yiyuan_id.mobileemr_transfer_interval_stop_yizhu_linshi");
			$stop_linshi_str = Utility::getIntervalSqlString('a.xiada_time' , $stop_linshi_interval);
			/*是否开启停止执行临时医嘱 开关*/
			/*是否开启 停止执行临时医嘱
			 on:开启
			 off:关闭
			 */
			$state_of_stop_linshi = Yaconf::get("config$yiyuan_id.state_of_stop_linshi");
			// 停止执行的临时医嘱配置
			if($state_of_stop_linshi == 'on'){
				$chaxun_linshi_where .= " and (a.state = '开始执行' and $linshi_str) or (a.state = '停止执行' and $stop_linshi_str )";
			}else{
				$chaxun_linshi_where .= "  and a.state = '开始执行' and $linshi_str ";
			}
			/*end*/
		}
		$filed_str_linshi = "a.id,a.zhuyuan_id,'临时' type,a.content,a.xiada_time as start_time,a.zhixing_time as stop_time,a.yongfa,a.yongfa_type,a.ciliang,a.shiyong_danwei,a.pinlv,a.zuhao,a.zhixing_state,a.yizhu_yongfa_type,a.meiri_cishu,a.wancheng_cishu,a.beizhu,a.xiangying_state,a.state,a.chushi_state,a.modify_time,a.shouci_yongyao,a.yongyao_time,a.shenhe_hushi_id";
		$sql = "SELECT $filed_str_linshi FROM zhuyuan_basic_info as t LEFT JOIN zhuyuan_yizhu_linshi AS a ON t.zhuyuan_id=a.zhuyuan_id WHERE $where_yiyuan_id $huanzhe_where $chaxun_linshi_where ";
		$zhuyuan_yizhu_linshi_data = DB::query(Database::SELECT, $sql)->execute()->as_array();
		//print_r($sql);exit;
        // $zhuyuan_yizhu_linshi_data = [];
		$yizhu_data = array();
		$yizhu_data = array_merge($zhuyuan_yizhu_changqi_data, $zhuyuan_yizhu_linshi_data);

		$async_result = array();
		$tiaoshu = 100;
		$now = date("y-m-d h:i:s", time());
		$today_date = date('Y-m-d');
		$today = strtotime($today_date);//获取前十位
		if($yizhu_data){
			//查询组号
			$zuhao_chaxun = array();
			$zuhao_str = "";
			$zuhao_last_state = [];//医嘱最后状态
			$zuhao_dangqian_cishu = [];//医嘱完成次数
			//查询最后一条操作记录的状态
			$order_by = " ORDER BY zhixing_zuhao ASC,dangqian_cishu ASC,case when zhixing_state in( '待配液' ,'已配液' , '拒绝执行') then 1
            when zhixing_state = '已校对' then 2 when zhixing_state = '开始执行' or zhixing_state = '暂停执行' then 3 when zhixing_state = '执行完毕' then 4 end ASC ,real_time ASC";
			$where_str_changqi = " AND `type`='长期' AND yizhu_time='$today_date' ";
			$where_str_linshi = " AND `type`='临时' ";
			foreach($yizhu_data as $k=>$v){
				$zuhao_chaxun[$v['zuhao']] = $v['zuhao'];
			}
			//查询当前最大完成次数
			$where_str = ' yiyuan_id = ' . $yiyuan_id . ' AND zhixing_zuhao IN (\'' . implode("','", $zuhao_chaxun) . '\')';
			/*长期*/
			$sql_1_cq = "SELECT zhixing_zuhao,zhixing_state FROM zhuyuan_yizhu_zhixing_history WHERE $where_str $where_str_changqi $order_by";
				
			$zuhao_last_state_cq = DB::query(Database::SELECT, $sql_1_cq)->execute()->as_array();
			if($zuhao_last_state_cq){
				foreach($zuhao_last_state_cq as $last_k=>$last_v){
					$zuhao_last_state[$last_v['zhixing_zuhao']] = $last_v['zhixing_state'];
				}
			}
			/*end*/
			/*临时*/
			$sql_1_ls = "SELECT zhixing_zuhao,zhixing_state FROM zhuyuan_yizhu_zhixing_history WHERE $where_str $where_str_linshi $order_by";
			$zuhao_last_state_ls = DB::query(Database::SELECT, $sql_1_ls)->execute()->as_array();
			if($zuhao_last_state_ls){
				foreach($zuhao_last_state_ls as $last_k=>$last_v){
					$zuhao_last_state[$last_v['zhixing_zuhao']] = $last_v['zhixing_state'];
				}
			}
			/*end*/
			$where_str .= " AND zhixing_state = '执行完毕'";
			// $where_str .= " AND case when type ='临时' then  1=1 else yizhu_time = '".$today_date."' end";
			/*临时当前最大完成次数*/
			$sql_linshi = "SELECT zhixing_zuhao,max(dangqian_cishu) as wancheng_cishu FROM zhuyuan_yizhu_zhixing_history WHERE $where_str $where_str_linshi GROUP BY zhixing_zuhao";
			$zuhao_dangqian_cishu_ls = DB::query(Database::SELECT, $sql_linshi)->execute()->as_array();
			if($zuhao_dangqian_cishu_ls){
				foreach($zuhao_dangqian_cishu_ls as $cishu_k=>$cishu_v){
					$zuhao_dangqian_cishu[$cishu_v['zhixing_zuhao']] = $cishu_v['wancheng_cishu'];
				}
			}
			/*end*/
			/*长期当前最大完成次数*/
				
			$sql_changqi = "SELECT zhixing_zuhao,max(dangqian_cishu) as wancheng_cishu FROM zhuyuan_yizhu_zhixing_history WHERE $where_str $where_str_changqi GROUP BY zhixing_zuhao";
			$zuhao_dangqian_cishu_cq = DB::query(Database::SELECT, $sql_changqi)->execute()->as_array();
			if($zuhao_dangqian_cishu_cq){
				foreach($zuhao_dangqian_cishu_cq as $cishu_k=>$cishu_v){
					$zuhao_dangqian_cishu[$cishu_v['zhixing_zuhao']] = $cishu_v['wancheng_cishu'];
				}
			}
			/*end*/
				
				
			//查询锁定信息
			$lock_zuhao = [];
			$lock_sql = "select zuhao,yizhu_time from zhuyuan_yizhu_lock where is_lock != 1 and yiyuan_id=".$this->yiyuan_id;
			$lock_zuhao = DB::query(Database::SELECT, $lock_sql)->execute()->as_array();
			if($lock_zuhao){
				foreach($lock_zuhao as $lock_k=>$lock_v){
					if($today_date == $lock_v['yizhu_time'] || !$lock_v['yizhu_time']){
						$lock_zuhao[$lock_v['zuhao']] = $lock_v;
					}
				}
			}
			$i = 0;
			$j = 0;
			foreach($yizhu_data as $key => $one_yizhu_info){
				$zuhao = $one_yizhu_info['zuhao'];
				//完成次数
				$wancheng_cishu = isset($zuhao_dangqian_cishu[$zuhao]) ? $zuhao_dangqian_cishu[$zuhao] : 0;
				$kuatian = isset($zuhao_last_state[$zuhao]) ? "否" : "是";
				$history_lishi_zhuangtai = isset($zuhao_last_state[$zuhao]) ? $zuhao_last_state[$zuhao] : $one_yizhu_info['chushi_state'];
				$yichang_lock = isset($lock_zuhao[$zuhao]) ? 1 : 0;
				//增加拒绝执行数据不返回处理
				if($history_lishi_zhuangtai == "拒绝执行"){
					continue;//增加拒绝执行的返回的数据不返回
				}
				if($j == $tiaoshu){//
					$i++;
					$j=0;
				}
				if($history_lishi_zhuangtai == "执行完毕"){
					$history_lishi_zhuangtai = $one_yizhu_info['chushi_state'];
				}

				$yongfa_type = $one_yizhu_info['yizhu_yongfa_type'];
				$zhixing_cishu['daily_need_number'] = $one_yizhu_info['meiri_cishu'];
				$zhixing_cishu['daily_finish_number'] = $wancheng_cishu;
				
				if($one_yizhu_info["type"] == "长期"){
					$temp_yizhu_id = '100'.$one_yizhu_info["id"];
				}else{
					$temp_yizhu_id = '200'.$one_yizhu_info["id"];
				}

				/*特殊字符转义*/
				if (get_magic_quotes_gpc()){
					$one_yizhu_info["content"] = $one_yizhu_info["content"];
				}else{
					$one_yizhu_info["content"] = addslashes($one_yizhu_info["content"]);
				}

				if($j == 0)
				{
					$async_result[$i] = "REPLACE INTO yizhu_info (yizhu_id,zhuyuan_id,yizhu_type,content,start_time,stop_time,yongfa,yongliang,shiyong_danwei,pinlv,zuhao,zhixing_state,meiri_cishu,wancheng_cishu,yongfa_type,kuatian,beizhu,xiangying_state,zhuangtai,yizhu_time,chushi_state,modify_time,shouci_yongyao,yongyao_time,yichang_lock,shenhe_hushi_id) SELECT  '".$temp_yizhu_id."','".$one_yizhu_info["zhuyuan_id"]."','".$one_yizhu_info["type"]."','".$one_yizhu_info["content"]."','".$one_yizhu_info["start_time"]."','".$one_yizhu_info["stop_time"]."','".$one_yizhu_info["yongfa"]."','".$one_yizhu_info["ciliang"]."','".$one_yizhu_info["shiyong_danwei"]."','".$one_yizhu_info["pinlv"]."','".$one_yizhu_info["zuhao"]."','".$history_lishi_zhuangtai."','".$zhixing_cishu['daily_need_number']."','".$zhixing_cishu['daily_finish_number']."','".$yongfa_type."','".$kuatian."','".$one_yizhu_info["beizhu"]."','".$one_yizhu_info["xiangying_state"]."','".$one_yizhu_info["state"]."','".$today_date."','".$one_yizhu_info["chushi_state"]."','".$one_yizhu_info["modify_time"]."','".$one_yizhu_info["shouci_yongyao"]."','".$one_yizhu_info["yongyao_time"]."','".$yichang_lock."','".$one_yizhu_info["shenhe_hushi_id"]."'";
				}
				else
				{
					$async_result[$i] .= " union all SELECT '".$temp_yizhu_id."','".$one_yizhu_info["zhuyuan_id"]."','".$one_yizhu_info["type"]."','".$one_yizhu_info["content"]."','".$one_yizhu_info["start_time"]."','".$one_yizhu_info["stop_time"]."','".$one_yizhu_info["yongfa"]."','".$one_yizhu_info["ciliang"]."','".$one_yizhu_info["shiyong_danwei"]."','".$one_yizhu_info["pinlv"]."','".$one_yizhu_info["zuhao"]."','".$history_lishi_zhuangtai."','".$zhixing_cishu['daily_need_number']."','".$zhixing_cishu['daily_finish_number']."','".$yongfa_type."','".$kuatian."','".$one_yizhu_info["beizhu"]."','".$one_yizhu_info["xiangying_state"]."','".$one_yizhu_info["state"]."','".$today_date."','".$one_yizhu_info["chushi_state"]."','".$one_yizhu_info["modify_time"]."','".$one_yizhu_info["shouci_yongyao"]."','".$one_yizhu_info["yongyao_time"]."','".$yichang_lock."','".$one_yizhu_info["shenhe_hushi_id"]."'";
				}
				$j++;
			}
		}
		return $async_result;
	}
}
